package com.niit.typehandlers;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
// 泛型 generic
public class ListTypeHandler extends BaseTypeHandler<List<String>> {
    // [唱歌,跳舞,画画,看电影] --> "唱歌;跳舞;画画;看电影;"
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> hobbies, JdbcType jdbcType) throws SQLException {
        StringBuilder stringBuilder = new StringBuilder();
        for(String hobby : hobbies){
            stringBuilder.append(hobby).append(";");
        }
        // 将 拼接好的 爱好的字符串， 设置到正在执行的 SQL语句的 第 i 个参数中，类型是String类型
        ps.setString(i, stringBuilder.toString());
    }

    // "唱歌;跳舞;画画;看电影;"-->唱歌,跳舞,画画,看电影]
    // ResultSet rs = ps.executeQuery("select * from user");
    @Override
    public List<String> getNullableResult(ResultSet resultSet, String hobbiesColumnName) throws SQLException {
        String[] hobbiesArr = resultSet.getString(hobbiesColumnName).split(";");
        List<String> hobbiesList = Arrays.asList(hobbiesArr);
        return hobbiesList;
    }
    // "唱歌;跳舞;画画;看电影;"-->唱歌,跳舞,画画,看电影]
    @Override
    public List<String> getNullableResult(ResultSet resultSet, int hobbiesColumnIndex) throws SQLException {
        String[] hobbiesArr = resultSet.getString(hobbiesColumnIndex).split(";");
        List<String> hobbiesList = Arrays.asList(hobbiesArr);
        return hobbiesList;
    }
    // "唱歌;跳舞;画画;看电影;"-->唱歌,跳舞,画画,看电影]
    @Override
    public List<String> getNullableResult(CallableStatement callableStatement, int hobbiesColumnIndex) throws SQLException {
        String[] hobbiesArr = callableStatement.getString(hobbiesColumnIndex).split(";");
        List<String> hobbiesList = Arrays.asList(hobbiesArr);
        return hobbiesList;
    }
}
